﻿/* File Created: July 27, 2012 */

;(function ($) {

	$.fn.zoomer = function (options) {

		if (this.length > 1) {
			this.each($(this).zoomer(options));
			return this;
		}

		var currentCell = null;
		var loading = false;
		var idleTime = 0;
		var zoomDisplayed = false;
		var displayCount = 0;
		var gridRow = null; 
		var idleInterval = null;
		var settings = {};

		this.init = function() {
			gridRow = $(this);
			settings = $.extend({},$.fn.zoomer.defaultOptions, options);
			this.attachElements();
			if (settings.autorun) {
				idleInterval = setInterval(idleTimerIncrement, 500);
			}
			gridRow.mouseleave(function () {
				hideZoom();
			});
			gridRow.parent().mouseenter(function() {
				hideZoom();
			});
			return this;
		};

		this.attachElements = function() {
			$(settings.selector).mouseenter(function () {
				currentCell = $(this);
			});
			$(settings.selector).mousemove(function () {
				/* idleTime = 0; */
			});
		};

		function idleTimerIncrement() {
			idleTime = idleTime + 500;
			if (idleTime > settings.timeout
				&& currentCell != null
				&& !zoomDisplayed)
			{
				showZoom();
			} 
		}

		function hideZoom() {
			idleTime = 0;
			currentCell = null;
			zoomDisplayed = false;
			gridRow.fadeOut();
			gridRow.hide();
		}

		function showZoom() {
			if (loading) {
				return;
			}
			loading = true;
			$("body").css('cursor', 'progress');
			var params = [ currentCell ];
			settings.onloading.apply(this,params);
			var data = settings.getData.apply(this,params);
			var coords = settings.getPosition.apply(this,params);
			gridRow.css({
				"top": coords.x,
				"left": coords.y
			});
			$.ajax({
				type: 'POST',
				contentType: 'application/json',
				url: settings.url,
				data: JSON.stringify(data),
				success: function (html) {
					$("body").css('cursor', 'auto');
					if (currentCell == null) {
						return;
					}
					gridRow.empty();
					gridRow.html(html);
					gridRow.fadeIn('slow');
					loading = false;
					zoomDisplayed = true;
					displayCount++;
					settings.onsuccess.apply(this,[currentCell, data]);
				},
				error: function() {
					$("body").css('cursor', 'auto');
				}
			});

			if (displayCount > 4) {
				settings.timeout = 500;
			} else if (displayCount > 2) {
				settings.timeout = 1000;
			}
		}

		return this.init();
	};

	$.fn.zoomer.defaultOptions = {
		selector : '',
		url : '',
		autorun : true,
		timeout : 1500,
		getData : function() { return null; },
		getPosition : function(element) { },
		onloading : function(element, data) { },
		onsuccess : function(element, data) { }
	};

})(jQuery);